// pages/begancar/begancar.js
var util = require('../../utils/sever.js');
var network = require('../../utils/network.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: [],
    imgurl: "../image/upimg.png",
    index: 0,
    carInforData: {},
    userInfor: "none",
    popuText: "",
    popuTextShow: false,
    carInoupt: "none",
    upcaridnumber: "",
    carInouptT: "block",





    //车牌选择
    carIdTypeNumbr: "0",
    //车牌输入
    carIdSelectNumbr: 0,
    //车牌类型
    IsNuew: 0,
    //车牌列表
    carIdType: [{
        "typeName": "普通牌"
      },
      {
        "typeName": "新能源牌"
      },
    ],
    //普通
    blueCard: ["", "", "", "", "", "", ""],
    //新能源
    NewCblueCardard: ["", "", "", "", "", "", "", ""],
    //车牌号属地
    CardAdders: ["京", "沪", "粤", "津", "浙", "苏", "湘", "渝",
      "云", "豫", "皖", "陕", "桂", "新", "青", "琼", "闽", "蒙",
      "辽", "鲁", "晋", "吉", "冀", "黑", "台", "甘", "赣", "贵",
      "川", "藏",
    ],
    CardLetter: ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
      "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
    ],
    CardNumber: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "挂", "学", "警", "港", "澳"],
    carmeal: [],
    carmealtype: 0,
    userIn: {},
    myCarCard: "",
    isShow: "none",
    isGeneralize: "none",
    yzms: 60,
    yzmclic: true,
    yzmnumber: false,
    phone: "",
    authcode: "",
    changeVIP: "立即充值",
    isChangeVIP: false,
    IsKeyShow: false,
    isShow: "none",
    yzmclic: true,
    yzmnumber: false,
    phone: "",
    authcode: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })

    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function(res) {
          if (res.confirm) {
            var pages = getCurrentPages() //获取加载的页面
            var currentPage = pages[pages.length - 1] //获取当前页面的对象
            var urll = currentPage.route + "" //当前页面url
            urll = urll.split("/")
            util.setToken("mypageTow", "../" + urll[1] + "/" + urll[2])
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    updateManager.onUpdateFailed(function() {
      // 新版本下载失败
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.useerInfor()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }, //扫一扫
  myScanCode: function() {
    var _this = this;

    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图
      sourceType: ['camera'], // 可以指定来源是相册还是相机
      success: function(res) {

        _this.setData({
          imgurl2: res.tempFiles[0].path
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        wx.showLoading({
          mask: true,
          title: "正在验证车牌",
        })
        wx.uploadFile({
          url: util.getRequestUrl + '/api/user/chePai', //仅为示例，非真实的接口地址
          filePath: res.tempFiles[0].path,
          name: 'fils',
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            "authorization": util.myToken("myToken")
          },
          formData: {},
          success(res) {
            var myres = JSON.parse(res.data)
            wx.hideLoading()
            if (myres.code == 200) {
              var jsonArr = [];
              for (var i = 0; i < myres.shoplist.length; i++) {
                jsonArr[i] = myres.shoplist[i].name;
              }
              _this.setData({
                carInforData: myres,
                array: jsonArr,
                userInfor: "blick",
                imgurl: _this.data.imgurl2
              })
            } else if (myres.code == 300) {
              wx.switchTab({
                url: '../index/index'
              })
            } else {
              _this.setData({
                userInfor: "none",
                popuTextShow: true,
                popuText: myres.msg,
                carInoupt: "block",
                carInouptT: "none",
                IsKeyShow: !_this.data.IsKeyShow
              })
              setTimeout(function() {
                _this.setData({
                  popuTextShow: false,
                })
              }, 6000)

            }
          }
        })
        // _this.detale(res)
      }
    })


  },
  //上传车牌
  upcarId: function() {
    var _this = this;
    var carid = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
    console.log(_this.data.upcaridnumber)
    var myCarId = ''
    if (_this.data.IsNuew == 0) {
      myCarId = _this.data.blueCard.join('')
    }
    if (_this.data.IsNuew == 1) {
      myCarId = _this.data.NewCblueCardard.join('')
    }
    if (!carid.test(myCarId)) {
      wx.showToast({
        icon: "none",
        title: '请输入正确车牌号',
      })
      return
    }
    wx.showLoading({
      mask: true,
      title: "正在验证车牌",
    })
    console.log(myCarId)
    console.log(_this.data.imgurl2)
    wx.uploadFile({
      url: util.getRequestUrl + '/api/user/ChepaiManual', //仅为示例，非真实的接口地址
      filePath: _this.data.imgurl2,
      name: 'fils',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        "authorization": util.myToken("myToken")
      },
      formData: {
        "vehicle_id": myCarId
      },
      success(res) {
        var myres = JSON.parse(res.data)
        wx.hideLoading()
        if (myres.code == 200) {
          var jsonArr = [];
          for (var i = 0; i < myres.shoplist.length; i++) {
            jsonArr[i] = myres.shoplist[i].name;
          }
          _this.setData({
            carInforData: myres,
            array: jsonArr,
            userInfor: "blick",
            imgurl: _this.data.imgurl2
          })
        } else if (myres.code == 300) {
          wx.switchTab({
            url: '../index/index'
          })
        } else {
          _this.setData({
            userInfor: "none",
            popuTextShow: true,
            popuText: myres.msg,
            carInoupt: "block"
          })
          setTimeout(function() {
            _this.setData({
              popuTextShow: false,
            })
          }, 6000)

        }
      }
    })
  },
  upcarIdNumber: function(e) {
    this.setData({
      upcaridnumber: e.detail.value
    })

  },
  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },
  goindex: function() {
    var _this = this;
    var data = {
      "wash_id": _this.data.carInforData.wash_log,
      "shop_id": _this.data.carInforData.shoplist[_this.data.index].id,
    }
    network.requestLoading(util.getRequestUrl + "/api/user/wash_noty", data, '', util.myToken("myToken"), function(res) {
        wx.showToast({
          icon: "none",
          title: res.msg,
        })
        setTimeout(function() {
          wx.switchTab({
            url: '../myinfor/myinfor'
          })
        }, 2000)
      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  //个人信息
  useerInfor: function() {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/user/getUserInfo", "", '正在加载数据', util.myToken("myToken"), function(res) {
        if (res.data.is_admin != 1) {
          wx.switchTab({
            url: '../index/index'
          })
        } else {
          _this.myScanCode()
        }
        // if (!res.data.is_info) {
        //   _this.getUserMyInfo()
        // }

      },
      function() {
        wx.showToast({
          icon: "none",
          title: '加载数据失败',
        })
      })
  },
  getUserMyInfo: function() {
    var _this = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // console.log(res)
              // 可以将 res 发送给后台解码出 unionId
              // res.userInfo
              var data = {
                nickname: res.userInfo.nickName ? res.userInfo.nickName : "",
                image: res.userInfo.avatarUrl ? res.userInfo.avatarUrl : ""
              }
              _this.upUser(data)
            }
          })
        } else {
          wx.redirectTo({
            url: '../authorization/authorization'
          })
        }
      }
    })
  },
  //车牌选择
  CarTypeSelect: function(e) {
    var _this = this;
    _this.setData({
      carIdSelectNumbr: 0,
      IsNuew: e.currentTarget.dataset.index,
      blueCard: ["", "", "", "", "", "", ""],
      NewCblueCardard: ["", "", "", "", "", "", "", ""],
      IsKeyShow: true
    })
  },
  //车牌归属地选择
  carIdAdders: function(e) {
    var _this = this;
    var myblueCard = _this.data.blueCard
    var myIsNuew = _this.data.IsNuew
    var myNumerUp = _this.data.carIdSelectNumbr
    if (myIsNuew == 1) {
      myblueCard = _this.data.NewCblueCardard
    }
    myblueCard[0] = _this.data.CardAdders[e.currentTarget.dataset.index]
    if (myIsNuew == 0) {
      _this.setData({
        blueCard: myblueCard,
        carIdSelectNumbr: myNumerUp + 1
      })
      return
    }
    _this.setData({
      NewCblueCardard: myblueCard,
      carIdSelectNumbr: myNumerUp + 1
    })
  },
  //字母选择
  carIdLetter: function(e) {
    var _this = this;
    var myLetter = e.currentTarget.dataset.index
    var myblueCard = _this.data.blueCard
    var myIsNuew = _this.data.IsNuew
    if (myIsNuew == 1) {
      myblueCard = _this.data.NewCblueCardard
    }
    var myNumerUp = _this.data.carIdSelectNumbr
    if (myNumerUp >= myblueCard.length) {
      return
    }
    if (myNumerUp < (myblueCard.length - 1)) {
      myNumerUp = myNumerUp + 1
    } else {
      myNumerUp = myNumerUp
    }
    myblueCard[_this.data.carIdSelectNumbr] = _this.data.CardLetter[myLetter]
    if (myIsNuew == 0) {
      _this.setData({
        blueCard: myblueCard,
        carIdSelectNumbr: myNumerUp
      })
      return
    }
    _this.setData({
      NewCblueCardard: myblueCard,
      carIdSelectNumbr: myNumerUp
    })
  },
  //字母选择
  carIdNumber: function(e) {
    var _this = this;
    var myNumber = e.currentTarget.dataset.index
    var myblueCard = _this.data.blueCard
    var myIsNuew = _this.data.IsNuew
    if (myIsNuew == 1) {
      myblueCard = _this.data.NewCblueCardard
    }
    var myNumerUp = _this.data.carIdSelectNumbr

    if (myNumerUp >= myblueCard.length) {
      return
    }
    if (myNumerUp < (myblueCard.length - 1)) {
      myNumerUp = myNumerUp + 1
    } else {
      myNumerUp = myNumerUp
    }

    myblueCard[_this.data.carIdSelectNumbr] = _this.data.CardNumber[myNumber]
    // console.log("myNumerUp" + myNumerUp)
    // console.log("myNumerUp" + _this.data.blueCard.length)
    if (myIsNuew == 0) {
      _this.setData({
        blueCard: myblueCard,
        carIdSelectNumbr: myNumerUp
      })
      return
    }
    _this.setData({
      NewCblueCardard: myblueCard,
      carIdSelectNumbr: myNumerUp
    })
  },
  //删除
  backGo: function() {
    var _this = this;
    var myNumber = _this.data.carIdSelectNumbr
    var myblueCard = _this.data.blueCard
    var myIsNuew = _this.data.IsNuew
    if (myIsNuew == 1) {
      myblueCard = _this.data.NewCblueCardard
    }
    if (myNumber <= 0) {
      return
    }
    myblueCard[(myNumber)] = ""
    if (myIsNuew == 0) {
      _this.setData({
        blueCard: myblueCard,
        carIdSelectNumbr: myNumber - 1
      })
      return
    }
    _this.setData({
      NewCblueCardard: myblueCard,
      carIdSelectNumbr: myNumber - 1
    })
  },
  backNo: function() {
    var _this = this;
    this.setData({
      IsKeyShow: !_this.data.IsKeyShow
    })
    _this.upcarId()
  },
})